package updown.domain;

import com.alibaba.fastjson.JSON;
import lombok.Builder;
import lombok.Data;
import org.springframework.util.StringUtils;
import updown.util.DateUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title: ww.kaixin.downupservice.domain </p>
 * <p>Description:updown: -  </p>
 *
 * @Author:jiangkaixin
 * @Date:2021/11/3
 * @Version: 1.0
 */
@Data
@Builder
public class TaskWrapper extends BaseEntity {
    /** 数据库字段 */
    @Builder.Default
    private String startTime = DateUtils.getCurDateTime();
    private String endTime;
    // 总耗时
    private String totalSpend;
    // 任务编号
    private String taskId;
    // 是否成功
    private Boolean success;
    // JarInfo
    private String jarInfo;
    // ServerHostInfo
    private String serverHostInfo;
    // ServiceInfo
    private String serviceInfoJson;
    private String serviceName;
    // Jar包上传、服务替换
    private String taskType;

    // 小任务列表
    @Builder.Default
    private List<TaskInfo> taskInfos = new ArrayList<>();
    // 对应的服务列表
    private List<ServerHost> serverHosts;
    // 替换的服务实例信息
    private ServiceInfo serviceInfo;
    // jar 包信息
    private Jar jar;
    // 重试类
    private DownUpRetry downUpRetry;
    // 定时任务
    private DownUpSchedule downUpSchedule;


    public void endSuccess(Boolean isSuccess) {
        this.success = isSuccess;
        this.endTime = DateUtils.getCurDateTime();
        this.totalSpend = String.valueOf(DateUtils.getSecondsBetweenNoError(this.startTime, this.endTime));
        this.jarInfo = jar != null ? jar.getVersion() : null;
        this.serviceInfoJson = serviceInfo != null ? JSON.toJSONString(serviceInfo) : null;
        this.serviceName = this.serviceInfo.getServiceName();
    }

    public void endFail() {
        this.success = Boolean.FALSE;
        this.endTime = DateUtils.getCurDateTime();
        this.totalSpend = String.valueOf(DateUtils.getSecondsBetweenNoError(this.startTime, this.endTime));
        this.jarInfo = jar != null ? jar.getVersion() : null;
        this.serverHostInfo = getServersInfo();
        this.serviceInfoJson = serviceInfo != null ? JSON.toJSONString(serviceInfo) : null;
        this.serviceName = this.serviceInfo.getServiceName();
    }

    private String getServersInfo() {
        if (serverHosts != null && !serverHosts.isEmpty()) {
            List<String> strings = serverHosts.stream().map(item -> {
                return item.getName() + "-" + item.getHost() + " ";
            }).collect(Collectors.toList());
            return strings.toString();
        }
        return "";
    }

    public String spendTime() {
        if (StringUtils.isEmpty(endTime)) {
            return String.valueOf(DateUtils.getSecondsBetweenNoError(this.startTime, DateUtils.getCurDateTime()));
        } else {
            return String.valueOf(DateUtils.getSecondsBetweenNoError(this.startTime, this.endTime));
        }
    }
}
